package com.zz.common.serialize;

import com.zz.common.annotation.Serialize;
import com.zz.common.entity.Meta;
import com.zz.common.enums.SerializationType;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

/**
 * protostuff 序列化实现
 *
 * @author zz
 */
@Serialize
@SuppressWarnings("all")
public class Protostuff extends SubstrateDispatcher {
    @Override
    public <T> byte[] serialize(T obj) throws Exception {
        Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(obj.getClass());
        return ProtostuffIOUtil.toByteArray(obj, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        T message = clazz.newInstance();
        Schema<T> schema = getSchema(clazz);
        ProtostuffIOUtil.mergeFrom(data, message, schema);
        return message;
    }

    private static <T> Schema<T> getSchema(Class<T> clazz) {
        return RuntimeSchema.getSchema(clazz);
    }

}
